﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;
using SilverTile;
using SilverTile.Xaml;
using SilverTile.ExtensionMethods;
using System.IO;
using System.Windows.Browser;
using System.Windows.Markup;
using SilverTile.Sprites;
using SilverTile.Viewports;
using System.Threading;

namespace SilverTileApp
{
    public partial class MainPage : UserControl
    {

        public MainPage()
        {
            InitializeComponent();
            Loaded += MainPage_Loaded;
            Game.PropertyChanged += Game_PropertyChanged;
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {            
            Game.Running = true;
        }

        void Game_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName.Equals("IsAlive"))
            {
                Dispatcher.BeginInvoke(() => MessageBox.Show("Game over"));
            }
        }

        private void UserControl_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Up:
                case Key.Right:
                case Key.Down:
                case Key.Left:
                    ((PlayerSprite)Game.GameWorld.PlayerSprite).Moving = false;
                    return;
            }
        }

        private void UserControl_KeyDown(object sender, KeyEventArgs e)
        {
            var player = (PlayerSprite)Game.GameWorld.PlayerSprite;

            switch (e.Key)
            {
                case Key.Up:
                    player.SetDirection(Direction.Up);
                    player.Moving = true;
                    return;
                case Key.Right:
                    player.SetDirection(Direction.Right);
                    player.Moving = true;
                    return;
                case Key.Down:
                    player.SetDirection(Direction.Down);
                    player.Moving = true;
                    return;
                case Key.Left:
                    player.SetDirection(Direction.Left);
                    player.Moving = true;
                    return;
                case Key.Space:
                    Game.ShowSword(player);
                    SwordSprite sword = (SwordSprite)Game.Viewport.ActiveSprites["Sword"];
                    player.Attack(() => sword.IsVisible = false);
                    break;
            }
        }

    }
}
